<script setup>
    import {ref} from 'vue'
    import useUserInfoStore from '@/stores/userInfo.js'
    import {useTokenStore} from '@/stores/token.js'
    import { ElMessage, ElMessageBox } from 'element-plus';
    import {useRouter} from 'vue-router'
    import {articlePageQueryService, articleInfoUpdateService, articleDeleteService, articleInfoGetService, articleRegisterService} from '@/api/article.js';
    import { Plus } from '@element-plus/icons-vue'

    const uploadRef = ref()
    const userInfoStore = useUserInfoStore();
    const tokenStore = useTokenStore();
    const router = useRouter();

    //列表的物品总数
    const itemsTotal = ref(1);
    

    //分页查询的表单结构
    const articlePageQueryData = ref({
        page: 1,
        pageSize: 5,
        id: null,
        title: null,
        content: null,
    })

    //定义表单校验规则
    const rules = {
        title: [
            { required: true, message: '标题不能为空', trigger: 'blur' },
        ],
        content: [
            { required: true, message: '内容不能为空', trigger: 'blur' },
        ],
        titleImage: [
            { required: true, message: '封面不能为空', trigger: 'blur' },
        ],
    }

    const articles = ref([])

    //分页查询获取列表
    const getarticles = async()=>{
        let result = await articlePageQueryService(articlePageQueryData.value);
        articles.value = result.records
        itemsTotal.value = result.total
    }
    //页面加载时获取一次所有
    getarticles()
    
    //分页大小改变时重新分页查询
    const handleSizeChange = (val) => {
        articlePageQueryData.value.pageSize = val
        getarticles()
    }
    //分页页码改变时重新分页查询
    const handleCurrentChange = (val) => {
        articlePageQueryData.value.page = val
        getarticles()
    }

    //是否在编辑用户，若为true则呼出右侧编辑窗口
    const isEditing = ref(false)
    //当前用户，用于承载编辑用户与添加用户的表单
    const currentarticle = ref({})

    const updateUserInfo = async ()=>{
    //调用接口
    let result = await articleInfoUpdateService(currentarticle.value);
    ElMessage.success(result.msg? result.msg : '修改成功');
    }

    //图片上传成功的回调函数
    const uploadSuccess = (result)=>{
        currentarticle.value.titleImage = result.data;
    }

    //编辑用户
    const editarticle = async (row) =>{
        isEditing.value = true   
        let result = await articleInfoGetService(row.id)
        currentarticle.value = result.data;
    }

    //删除用户使用ElMessageBox判断
    const deletearticle = (row) =>{
        ElMessageBox.confirm(
            '要删除该文章吗?',
            'Warning',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then( async () => {
                let id = row.id;
                let result = await articleDeleteService(id)
                ElMessage.success(result.msg? result.msg : '删除成功');
                getarticles()
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })

    }

    //取消编辑
    const cancelClickEditing = () =>{
        isEditing.value = false
    }

    //提交编辑
    const confirmClickEditing = async () =>{
        await updateUserInfo()
        isEditing.value = false
        await getarticles()
    }

    //是否在添加新用户，若为true则呼出右侧新增用户窗口
    const isAdding = ref(false)

    const addarticle = async() => {
         //调用接口
        currentarticle.value.repeatPassword = currentarticle.value.password
        let result = await articleRegisterService(currentarticle.value);
        ElMessage.success(result.msg? result.msg : '新增成功');
    }

    
    //添加，初始化表单
    const addarticleButton = () =>{
        currentarticle.value = {
            id: null,
            title: null,
            content: null,
        }
        isAdding.value = true;
    }

    //取消新增
    const cancelClickAdding = () =>{
        isAdding.value = false
    }

    //提交新增
    const confirmClickAdding = async () =>{
        await addarticle()
        isAdding.value = false
        await getarticles()
    }



</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>文章管理</span>
            </div>
        </template>

        <div>
            <!-- 顶部栏，包含分页查询过滤条件，以及创建新用户 -->
            <el-form class="search-filter" :model="articlePageQueryData">
                <el-form-item label="ID">
                    <el-input v-model="articlePageQueryData.id" type="number"></el-input>
                </el-form-item>
                <el-form-item label="文章标题">
                    <el-input v-model="articlePageQueryData.title" type="text"></el-input>
                </el-form-item>
                <el-form-item>
                        <el-button type="primary" @click="getarticles">搜索</el-button>
                </el-form-item>
                <el-form-item>
                        <el-button @click="addarticleButton">新增</el-button>
                </el-form-item>
            </el-form>
        </div>

        <hr style="background-color: #eee; height: 1px; border: none;"/>

        <!-- 表格 -->
        <el-table :data="articles" style="width: 100%">
            <el-table-column prop="id" label="ID" width="180" sortable  />
            <el-table-column prop="title" label="文章标题" width="350" sortable  />
            <el-table-column prop="content" label="文章内容" width="500" sortable />
            <el-table-column prop="operations" label="操作" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="editarticle(scope.row)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="deletearticle(scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <!-- 页码切换组件 -->
        <div class="pagination-block">
            <el-pagination layout="prev, pager, next, sizes" :total="itemsTotal" :page-size="articlePageQueryData.pageSize"
            v-model:current-page="articlePageQueryData.page"
            v-model:page-size="articlePageQueryData.pageSize"
            
            :page-sizes="[5, 10, 20, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
    </el-card>

    <!-- 新增侧边界面 -->
    <el-drawer v-model="isEditing" :direction="rtl" size="50%">
        <template #header>
            <h4>编辑文章</h4>
        </template>
        <template #default>
            <div class="form-edit-message" >
                <el-row>
                    <el-col :span="18">

                        <el-form :model="currentarticle" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="ID">
                                <el-input v-model="currentarticle.id" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="文章标题" prop="title">
                                <el-input v-model="currentarticle.title"></el-input>
                            </el-form-item>
                            <el-form-item label="文章封面" prop="image">
                                <div class="form-edit-image">
                                    <el-upload
                                    class="avatar-uploader"
                                    action="/api/upload"
                                    :show-file-list="false"
                                    :on-success="uploadSuccess"
                                    >
                                        <img v-if="currentarticle.titleImage" :src="currentarticle.titleImage" class="avatar" />
                                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                                    </el-upload>
                                </div>
                            </el-form-item>
                            <el-form-item label="文章内容" prop="content">
                                <el-input type="textarea" v-model="currentarticle.content"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="cancelClickEditing">取消</el-button>
            <el-button type="primary" @click="confirmClickEditing">确认</el-button>
        </div>
        </template>
  </el-drawer>


  <!-- 新增通知的侧边界面 -->
  <el-drawer v-model="isAdding" :direction="rtl" size="50%">
        <template #header>
            <h4>新增文章</h4>
        </template>
        <template #default>
            <div class="form-edit-message" >
                <el-row>
                    <el-col :span="18">
                        <el-form :model="currentarticle" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="文章标题" prop="title">
                                <el-input v-model="currentarticle.title"></el-input>
                            </el-form-item>
                            <el-form-item label="文章封面" prop="image">
                                <div class="form-edit-image">
                                    <el-upload
                                    class="avatar-uploader"
                                    action="/api/upload"
                                    :show-file-list="false"
                                    :on-success="uploadSuccess"
                                    >
                                        <img v-if="currentarticle.titleImage" :src="currentarticle.titleImage" class="avatar" />
                                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                                    </el-upload>
                                </div>
                            </el-form-item>
                            <el-form-item label="文章内容" prop="content">
                                <el-input type="textarea" v-model="currentarticle.content"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="cancelClickAdding">取消</el-button>
            <el-button type="primary" @click="confirmClickAdding">确认</el-button>
        </div>
        </template>
  </el-drawer>

</template>

<style scoped>
    .search-filter {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }

    .pagination-block{
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .form-edit-message {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .form-edit-message .el-input__inner {
        min-height: 100px; /* 增加输入框的高度 */
    }

    .form-edit-image {
        display: flex;
        justify-content: center;
        padding: 32px;
        overflow: hidden;
        width: 356px;
        height: 178px;
    }

    .avatar-uploader .el-upload {
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.1s ease-in-out;
        width: 356px;
        height: 178px;
        overflow: hidden;
    }
    .avatar {
        width: 100%;
        height: 100%;
    }


    .el-icon.avatar-uploader-icon:hover {
        border-color: #409EFF;
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        text-align: center;
        border: 1px dashed #888;
        border-radius: 6px;
        transition: all 0.1s ease-in-out;
        width: 356px;
        height: 178px;
    }

</style>